#include <stdio.h>
#include <malloc.h>

struct node {
	struct node *next;
	int val;
};

struct node *head = NULL;

struct node *initialize_list(struct node *head, int count)
{
	struct node *p1;
	int i;

	if (!count || head)
		return head;

	head = malloc(sizeof(*head));
	head->val = 999;
	head->next = NULL;
	p1 = head;

	for (i = 1; i < count; i++) {
		struct node *p = malloc(sizeof(*p));
		p->val = i;
		p->next = NULL;

		p1->next = p;
		p1 = p;
	}

	return head;
}

struct node *reverse_list(struct node *head)
{
	struct node *p1, *p2, *p3;

	if (!head)
		return NULL;

	if (!head->next)
		return head;

	p1 = head;
	p2 = head->next;
	p3 = NULL;

	do {
		p1->next = p3;
		p3 = p1;
		p1 = p2;
		p2 = p2->next;
	} while (p2);

	p1->next = p3;

	return p1;
}

void print_list(struct node *head)
{
	struct node *p = head;

	while (p) {
		printf("%d ", p->val);
		p = p->next;
	}
	printf("\n");
}

int main(void)
{
	head = initialize_list(head, 0);
	print_list(head);

	head = reverse_list(head);
	print_list(head);

	return 0;
}

